package com.zhiqianbao.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.creditx.xbehavior.sdk.ActionName;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.creditx.xbehavior.sdk.PageName;
import com.google.gson.JsonIOException;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserPhoneCheck;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.PermissionDialog;
import com.zhiqianbao.utils.PermissionsManager;
import com.zhiqianbao.utils.ScreenManager;
import com.zhiqianbao.utils.T;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.view.ProcessProgressBarView;

import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/10/9.
 */
public class BindPhoneConfirmActivity extends BaseActivity implements View.OnClickListener {
    TextView tipTextView;
    /**
     * 运营商手机号
     */
    TextView textViewPhoneNumberContent;
    /**
     * 密码输入框
     */
    EditText textViewPhonePasswordContent;

    /**
     * 运营商密码输入布局
     */
    RelativeLayout yunyingPwLayout;
//    /**
//     * 错误提示信息布局
//     */
//    @Bind(R.id.text_view_tip_content)
//    TextView tipTextView;

    /**
     * 验证码输入布局
     */
    RelativeLayout phoneSmscodeLayout;
    /**
     * 验证码输入框
     */
    EditText codeContent;
    /**
     * 用户信息输入布局
     */
    RelativeLayout userMsgLayout;
    /**
     * 姓名输入框
     */
    EditText nameContent;

    /**
     * 身份证输入框
     */
    EditText idcardContent;

    /**
     * 确认按钮
     */
    Button buttonConfirm;
    /**
     * 步骤头布局
     */
    ProcessProgressBarView processView;
    /**
     * 进度加载图片
     */
    GifView gif_loading;
    private SharedPreferanceUtils sharedPreferanceUtils;
    private static  final  int YUNYING_PW_CONFIRM=1;//运营商密码提交
    private static  final  int SMSCODE_CONFIRM=2;//手机短信验证提交
    private static  final  int USER_MSG_CONFIRM=3;//用户信息提交
    private int confirmType=1;//用户操作提交按钮类型
    private AlertDialog timeDialog;
    private AlertDialog msgDialog;
    private Handler timeHandle = null;
    private boolean smsCodeIsShowing=false;//弹出了短信验证码输入页面
    /**
     * 定时器刷新查询接口轮询时间
     */
    Integer time = 5000;
    /**
     * 每次轮询20秒后提示用户是否进入下一步
     */
    Integer reTimes = 0;
    /**
     * 运营商平台类型
     * 3墨盒，1信数
     */
    private String type = "3";
    /**
     * 提示信息
     */
    private String tipText;
    /**
     * 需要
     */
    private String need;
    /**
     * 判断是否是从修改手机页面跳转
     * true是跳转；false是信息资料页面跳转
     */
    private boolean intentChangePhone=false;
    private String startTimes="";
    /**
     * 定时器，定时查询用户状态
     */
    private Runnable timer = new Runnable() {
        @Override
        public void run() {
            if (reTimes == 20000) {
                reTimes = 0;
                if(!smsCodeIsShowing) {
                    if(!isFinishing()) {
                        nextPageDialog();
                    }
                }
                cancelTimer();
            } else {
                reTimes = reTimes + 5000;
                phoneQueryNew();
                timeHandle.postDelayed(this, time);
            }
        }
    };

    //提交通话详单功能
    Handler commitHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Result<String> data = (Result<String>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            String state = data.getData();
                            //提交成功，跳转到等待处理页面
                            if (Constants.STATE_OK.equals(state)) {
                                CreditXAgent.onSubmit(ActionName.Submit.OPERATOR,
                                        CreditXAgent.ActionStatus.SUCCESS, "提交成功");
                                String status=Constants.CALL_DETAILS_STATUS_PROCESSING;
                                need="";
                                tipText="";
                                switchState(status);
                                //跳转其他页面后关闭身份证验证页面
                            } else {
                                CreditXAgent.onSubmit(ActionName.Submit.OPERATOR,
                                        CreditXAgent.ActionStatus.FAILED, "提交失败");
                            }

                        } else {
                            CreditXAgent.onSubmit(ActionName.Submit.OPERATOR,
                                    CreditXAgent.ActionStatus.FAILED, "提交失败");
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
                case 0:
                    CreditXAgent.onSubmit(ActionName.Submit.OPERATOR,
                            CreditXAgent.ActionStatus.FAILED, "提交失败");
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
        }
    };

    @Override
    protected void
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone_confirm);
        //开始统计进入运营商验证页面时间
        startTimes=TimeStatisticsUtil.getTime();
        checkPermission_v4(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS);
        init();
        initView();
        phoneCheck();
    }

    private PermissionDialog permissionDialog;
    private PermissionsManager perManager;

    private boolean checkPermission_v4(final String... permission) {
        if (perManager == null)
            perManager = new PermissionsManager(this, new PermissionsManager.PermissionListener() {
                // 添加权限请求返回监听器并内置了一个二次提示框
                @Override
                public void getRequestPermissionCallBack(String[] permissions, boolean isAgree) {
                    // 权限没有全部获取
                    if (!isAgree) {
                        final String[] p = permissions;
                        // 向用户弹出一个提示框,包含确定和取消两个按钮
                        if (permissionDialog == null)
                            permissionDialog = new PermissionDialog(getApplicationContext(), new PermissionDialog.PermissionCheckListener() {

                                @Override
                                public void userChoosed(boolean isChooseOk) {
                                    if (isChooseOk) {// 点击确定
                                        // 先检查一下有没有完全禁止，有的话那就拜拜了您那~~ 让系统安全应用去处理吧
                                        checkShouldShowPermission(p);
                                        // 没有就再次检查指导结束
                                        checkPermission_v4(permission);
                                    } else {// 点击取消
                                        // 关闭页面
                                    }
                                }
                            });
                        permissionDialog.show();
                    }
                }
            });
        // 检查是否已有权限
        return perManager.checkPermission(permission);
    }

    /**
     * 检查是否可以显示权限授予对话框
     *
     * @param permissions
     * @author Wall
     */
    public void checkShouldShowPermission(String[] permissions) {
        if (perManager != null) {
            // 检查是否已被禁止
            boolean isNeedShow = perManager.checkShouldShowPermission(permissions);
            if (isNeedShow) {
                T.getInstanse(this).showLong(R.string.exception_nopermission);
            }
        }
    }


    public boolean checkPermission_v4(final PermissionsManager.PermissionListener listener, final String... permission) {
        if (perManager == null)
            perManager = new PermissionsManager(this, listener);
        return perManager.checkPermission(permission);
    }

    private void initView() {
         tipTextView=(TextView)findViewById(R.id.text_view_tip_content);
         textViewPhoneNumberContent=(TextView)findViewById(R.id.textView_phone_number_content);
         textViewPhonePasswordContent=(EditText)findViewById(R.id.textView_phone_password_content);
         yunyingPwLayout=(RelativeLayout)findViewById(R.id.yunying_pw_layout);
         phoneSmscodeLayout=(RelativeLayout)findViewById(R.id.phone_smscode_layout);
         codeContent=(EditText)findViewById(R.id.textView_code_content);
         userMsgLayout=(RelativeLayout)findViewById(R.id.user_msg_layout);
         nameContent=(EditText)findViewById(R.id.textView_name_content);
         idcardContent=(EditText)findViewById(R.id.textView_idcard_content);
         buttonConfirm=(Button)findViewById(R.id.button_confirm);
         processView=(ProcessProgressBarView)findViewById(R.id.process_layout);
         gif_loading=(GifView)findViewById(R.id.gif_loading);

        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        try {
            String userName = sharedPreferanceUtils.getName();
            String phone = sharedPreferanceUtils.getPhoneNuber();
            textViewPhoneNumberContent.setText(Constants.LOGIN_USER.getPhone());
        } catch (Exception e) {

        }
        textViewPhonePasswordContent.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.OPERATOR_SERVICE_PASSWORD));

        buttonConfirm.setOnClickListener(this);
        gif_loading= (GifView) findViewById(R.id.gif_loading);
        processView = (ProcessProgressBarView) findViewById(R.id.process_layout);
        // 设置Gif图片源
        gif_loading.setGifImage(R.drawable.loading_1);

        Intent intent=getIntent();
        if(intent.hasExtra("intentChangePhone")){
            intentChangePhone=intent.getBooleanExtra("intentChangePhone",false);
        }
        if(intentChangePhone){
            processView.setVisibility(View.GONE);
        }
        else{
            //芝麻开启状态,1开启，0未开启
            String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
            if ("1".equals(zhimaOpenOrClose)) {
                processView.openZhiMaProcess(ProcessProgressBarView.IS_SHOW_ZHIMA, 2);
            } else {
                processView.openZhiMaProcess(ProcessProgressBarView.NOTIS_SHOW_ZHIMA, 2);
            }
            processView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        if(R.id.button_confirm==v.getId()){
                //记录当前时间
                Constants.prevCheckTimeMillis = System.currentTimeMillis();
                String code = codeContent.getText().toString();
                String name = nameContent.getText().toString();
                String idcard = idcardContent.getText().toString();
                smsCodeIsShowing=false;
                if(confirmType==YUNYING_PW_CONFIRM) {
                    final String password = textViewPhonePasswordContent.getText().toString();
                    if (StringUtils.isBlank(password)) {
                        showShortToast1("请输入运营商密码");
                        return;
                    }
                    buttonConfirm.setBackgroundResource(R.drawable.activity_apply_index_want_to_express_normal_icon);
                    buttonConfirm.setClickable(false);
                    gif_loading.setVisibility(View.VISIBLE);
                    phoneCommitNew(password);
                }
                else if(confirmType==SMSCODE_CONFIRM){
                    smsCodeIsShowing=false;
                    //需要验证码
                    if (StringUtils.isBlank(code)) {
                        showShortToast1("请输入验证码");
                        return;
                    }
                    phoneUpdateNew(code,name,idcard);
                }
                else if(confirmType==USER_MSG_CONFIRM){
                    //需要填写姓名省份证号
                    if (StringUtils.isBlank(name)) {
                        showShortToast1("请输入姓名");
                        return;
                    }
                    if (StringUtils.isBlank(idcard)) {
                        showShortToast1("请输入身份证号");
                        return;
                    }
                    phoneUpdateNew(code,name,idcard);
                }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CreditXAgent.onEnteringPage(PageName.OPERATOR);
    }

    @Override
    public void onPause() {
        super.onPause();
        CreditXAgent.onLeavingPage(PageName.OPERATOR);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimer();
        if (timer != null) {
            timer = null;
        }
    }

    public void phoneCommitNew(final String password){
        //调用提交任务接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message commitMessage = new Message();
                Map<String, String> params = new HashMap<>();
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("password", password);
                //添加时间统计
                String endTime = TimeStatisticsUtil.getTime();
                params.put("startTime", startTimes);
                params.put("endTime", endTime);

                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/commitNew", params, BindPhoneConfirmActivity.this);
                if (!TextUtils.isEmpty(result)) {
                    Log.i("BindPhoneConfirm1", "" + result);
                } else {
                    Log.i("BindPhoneConfirm1", "这是空");
                }
                if (StringUtils.isBlank(result)) {
                    commitMessage.what = 0;
                } else {
                    commitMessage.what = 1;
                    Result<String> data = Result.fromJson(result, String.class);
                    commitMessage.obj = data;
                }
                commitHandle.sendMessage(commitMessage);
            }
        }).start();
    }
    public void phoneCheck() {
        showWaitDialog();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message phoneCheckMessage = new Message();
                Map<String, String> params = new HashMap<>();
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone() + "" : "");
                //1.0.7
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/checkNew", params, BindPhoneConfirmActivity.this);
                if (!TextUtils.isEmpty(result)) {
                    Log.i("BindPhoneConfirm", "" + result);
                } else {
                    Log.i("BindPhoneConfirm", "这是空");
                }
                if (StringUtils.isBlank(result)) {
                    phoneCheckMessage.what = 0;
                } else {
                    phoneCheckMessage.what = 1;
                    Result<UserPhoneCheck> data = Result.fromJson(result, UserPhoneCheck.class);
                    phoneCheckMessage.obj = data;
                }
                userPhoneCheckHandler.sendMessage(phoneCheckMessage);
            }
        }).start();
    }


    Handler userPhoneCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            closeWaitDialog();
            switch (msg.what) {
                case 1:
                    try {
                        Result<UserPhoneCheck> data = (Result<UserPhoneCheck>) msg.obj;
                        if (data == null) {
                            return;
                        }
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            UserPhoneCheck userPhoneCheck = data.getData();
                            //还没有进行手机验证，跳转到输入手机号信息的页面
                            if (userPhoneCheck == null) {
                                return;
                            }
                            //已经验证，但是需要进行下一步处理，跳转到下一步处理页面
                            String status = userPhoneCheck.getStatus() != null ?
                                    userPhoneCheck.getStatus() : "";
                            String reason = userPhoneCheck.getReason() != null ?
                                    userPhoneCheck.getReason() : "";
                            if (Constants.CALL_DETAILS_STATUS_SUSPENDED.equals(status) ||
                                    (Constants.CALL_DETAILS_STATUS_PROCESSING.equals(status))) {
                                need=userPhoneCheck.getNeed()!=null ? userPhoneCheck.getNeed():"";
                                tipText=reason;
                                type=userPhoneCheck.getType()!=null ? userPhoneCheck.getType():"";
                                //判断状态，改变显示
                                switchState(status);
                            }
                            else if(Constants.CALL_DETAILS_STATUS_UPCFAILED.equals(status)){
                                if(!TextUtils.isEmpty(reason)){
                                    if(!isFinishing()) {
                                        failReasonMsg(reason);
                                    }
                                }
                            }
                            else{
                                nextPage();
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    } catch (JsonIOException exception) {

                    } catch (NullPointerException exception) {

                    }
                    break;
                case 0:
//                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
        }
    };

    public void phoneQueryNew(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message phoneCheckMessage = new Message();
                Map<String, String> params = new HashMap<>();
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone() + "" : "");

                //1.0.7
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/queryNew", params, BindPhoneConfirmActivity.this);
                if (!TextUtils.isEmpty(result)) {
                    Log.i("BindPhoneStatusInfo1", "" + result);
                } else {
                    Log.i("BindPhoneStatusInfo1", "这是空");
                }
                if (StringUtils.isBlank(result)) {
                    phoneCheckMessage.what = 0;
                } else {
                    phoneCheckMessage.what = 1;
                    Result<UserPhoneCheck> data = Result.fromJson(result, UserPhoneCheck.class);
                    phoneCheckMessage.obj = data;
                }
                userPhoneQueryHandler.sendMessage(phoneCheckMessage);
            }
        }).start();
    }

    Handler userPhoneQueryHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Result<UserPhoneCheck> data = (Result<UserPhoneCheck>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            UserPhoneCheck userPhoneCheck = data.getData();
                            //还没有进行手机验证，跳转到输入手机号信息的页面
                            if (userPhoneCheck == null) {
                                return;
                            }
                            String state=userPhoneCheck.getStatus()!=null ? userPhoneCheck.getStatus():"";
                            need=userPhoneCheck.getNeed()!=null ? userPhoneCheck.getNeed():"";
                            tipText=userPhoneCheck.getReason()!=null ? userPhoneCheck.getReason():"";
                            type=userPhoneCheck.getType()!=null ? userPhoneCheck.getType():"";

                            if (Constants.CALL_DETAILS_STATUS_DONE.equals(state)) {
                                closeWaitDialog();
                                nextPage();
                            } else {
                                switchState(state);
                                closeWaitDialog();
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
                case 0:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
        }
    };

    public void phoneUpdateNew(final String code, final String name, final String idcard){
        showWaitDialog();
        //调用更新任务按钮
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message updateTaskMessage = new Message();
                Map<String, String> params = new HashMap<>();
                //public Result<String> updateCallTask(Long userId, String phone, String smsCode, String password, String userName, String idcard) {
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("phone", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getPhone() + "" : "");
                params.put("smsCode", code);
                params.put("password", "");
                params.put("userName", name);
                params.put("idcard", idcard);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/phone/updateNew", params, BindPhoneConfirmActivity.this);
                if (!TextUtils.isEmpty(result)) {
                    Log.i("BindPhoneStatusInfo2", "" + result);
                } else {
                    Log.i("BindPhoneStatusInfo2", "这是空");
                }
                if (StringUtils.isBlank(result)) {
                    updateTaskMessage.what = 0;
                } else {
                    updateTaskMessage.what = 1;
                    Result<String> data = Result.fromJson(result, String.class);
                    updateTaskMessage.obj = data;
                }
                updateTaskHandler.sendMessage(updateTaskMessage);
            }
        }).start();
    }

    Handler updateTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Result<String> data = (Result<String>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            String state = data.getData();
                            //提交成功，跳转到等待处理页面
                            if (Constants.STATE_OK.equals(state)) {
                                need="";
                                tipText="";
                                //更新状态和显示
                                switchState(Constants.CALL_DETAILS_STATUS_CODEAFTER_PROCESSING);
                                //提交失败，提示用户
                            } else {
                                showShortToast1("提交失败，请稍候再试。");
                            }
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
                case 0:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
            closeWaitDialog();
        }

    };


    private void switchState(String state) {
        //根据state不同显示不同内容
        if ("3".equals(type)) {
            if (!TextUtils.isEmpty(tipText)) {
                tipTextView.setVisibility(View.VISIBLE);
                tipTextView.setText(tipText);
            }
        }
        switch (state) {
            case Constants.CALL_DETAILS_STATUS_PROCESSING:
                buttonConfirm.setBackgroundResource(R.drawable.activity_apply_index_want_to_express_normal_icon);
                buttonConfirm.setClickable(false);
                gif_loading.setVisibility(View.VISIBLE);
                tipText = "系统正在处理请稍等……";
                //启动定时器
                beginTimer();
                break;
            case Constants.CALL_DETAILS_STATUS_CODEAFTER_PROCESSING:
                smsCodeIsShowing=true;
                //取消定时器
                cancelTimer();
                nextPage();
                buttonConfirm.setBackgroundResource(R.drawable.i_btn_big_normal);
                buttonConfirm.setClickable(true);
                gif_loading.setVisibility(View.GONE);
                break;
            case Constants.CALL_DETAILS_STATUS_FAILED:
                smsCodeIsShowing=true;
                tipText = "认证失败，请重试！";
                //取消定时器
                cancelTimer();
                //隐藏其他
                confirmType=YUNYING_PW_CONFIRM;
                yunyingPwLayout.setVisibility(View.VISIBLE);
                phoneSmscodeLayout.setVisibility(View.GONE);

                buttonConfirm.setBackgroundResource(R.drawable.i_btn_big_normal);
                buttonConfirm.setClickable(true);
                gif_loading.setVisibility(View.GONE);
                tipTextView.setVisibility(View.GONE);
                //显示认证失败
                if(!isFinishing()){
                    if (!TextUtils.isEmpty(tipText)) {
                        failReasonMsg(tipText);
                    }
                }
                break;
            case Constants.CALL_DETAILS_STATUS_UPCFAILED:
                smsCodeIsShowing=true;
                //取消定时器
                cancelTimer();
                //隐藏其他
                confirmType=YUNYING_PW_CONFIRM;
                yunyingPwLayout.setVisibility(View.VISIBLE);
                phoneSmscodeLayout.setVisibility(View.GONE);
                userMsgLayout.setVisibility(View.GONE);

                buttonConfirm.setBackgroundResource(R.drawable.i_btn_big_normal);
                buttonConfirm.setClickable(true);
                gif_loading.setVisibility(View.GONE);
                //显示认证失败
                if(!isFinishing()){
                    if (!TextUtils.isEmpty(tipText)) {
                        failReasonMsg(tipText);
                    }
                }
                break;
            case Constants.CALL_DETAILS_STATUS_SUSPENDED:
                smsCodeIsShowing=true;
                buttonConfirm.setBackgroundResource(R.drawable.i_btn_big_normal);
                buttonConfirm.setClickable(true);
                gif_loading.setVisibility(View.GONE);
                //取消定时器
                cancelTimer();

                if (Constants.smsReasonMap.containsKey(need)) {
                    //需要验证码
                    confirmType=SMSCODE_CONFIRM;
                    typeShowTv(Constants.smsReasonMap);
                    yunyingPwLayout.setVisibility(View.GONE);
                    phoneSmscodeLayout.setVisibility(View.VISIBLE);
                    userMsgLayout.setVisibility(View.GONE);
                } else if (Constants.nameReasonMap.containsKey(need)) {
                    //需要填写姓名身份证号
                    confirmType=USER_MSG_CONFIRM;
                    typeShowTv(Constants.nameReasonMap);
                    yunyingPwLayout.setVisibility(View.GONE);
                    phoneSmscodeLayout.setVisibility(View.GONE);
                    userMsgLayout.setVisibility(View.VISIBLE);
                } else if (Constants.passwordReasonMap.containsKey(need)) {
                    //需要再次输入服务密码
                    confirmType=YUNYING_PW_CONFIRM;
                    typeShowTv(Constants.passwordReasonMap);
                    yunyingPwLayout.setVisibility(View.VISIBLE);
                    phoneSmscodeLayout.setVisibility(View.GONE);
                    userMsgLayout.setVisibility(View.GONE);
                }
                break;
        }

    }

    public void typeShowTv(Map<String,String> maps){
        if (!"3".equals(type)) {
            if (TextUtils.isEmpty(tipText)) {
                if(!TextUtils.isEmpty(need)) {
                    tipTextView.setVisibility(View.VISIBLE);
                    tipTextView.setText(maps.get(need));
                }
            }
            else{
                tipTextView.setVisibility(View.VISIBLE);
                tipTextView.setText(tipText);
            }
        }
    }

    /**
     * 轮询20秒后，提示用户是否进入下一步页面
     */
    public void nextPageDialog() {
        if (timeDialog == null) {
            timeDialog = new AlertDialog.Builder(BindPhoneConfirmActivity.this, R.style.Dialog).create();
            timeDialog.show();
            View view = LayoutInflater.from(BindPhoneConfirmActivity.this).inflate(R.layout.dialog_express_coupon_layout, null);
            timeDialog.getWindow().setContentView(view);
            TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
            Button button = (Button) view.findViewById(R.id.positiveButton);
            Button cacelButton = (Button) view.findViewById(R.id.cacelButton);
            repay_money.setText("验证申请已提交，您可以选择继续等待验证结果，也可以进行其他验证，是否等待？");
            button.setText("下一步");
            cacelButton.setText("等待");
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    timeDialog.dismiss();
                    timeDialog=null;
                    nextPage();
                }
            });

            cacelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    reTimes = 0;
                    timeDialog.dismiss();
                    timeDialog=null;
                    beginTimer();
                }
            });
        }
    }

    public void nextPage() {
        if(intentChangePhone) {
            ScreenManager.getScreenManager().popItemActivityExceptOne(ChangePhoneActivity.class);
            finish();
            return;
        }
        String emergency = sharedPreferanceUtils.getEmergency();
        String jobState = sharedPreferanceUtils.getJobState();
        String zhima_state = sharedPreferanceUtils.getZhiMaState();//芝麻信用
        if (!TextUtils.isEmpty(emergency)) {
            //芝麻开启状态,1开启，0未开启
            String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
            if ("1".equals(zhimaOpenOrClose)) {
                if ("1".equals(zhima_state) || "2".equals(zhima_state)) {
                    if ("1".equals(emergency) || "2".equals(emergency)) {
                        if ("1".equals(jobState) || "2".equals(jobState)) {
                            finish();
                        } else {
                            startActivity(new Intent(BindPhoneConfirmActivity.this, FourthActivity.class));
                            finish();
                        }
                    } else {
                        startActivity(new Intent(BindPhoneConfirmActivity.this, ThirdActivity.class));
                        finish();
                    }
                } else {
                    startActivity(new Intent(BindPhoneConfirmActivity.this, ZhiMaActivity.class));
                    finish();
                }
            } else {
                if ("1".equals(emergency) || "2".equals(emergency)) {
                    if ("1".equals(jobState) || "2".equals(jobState)) {
                        finish();
                    } else {
                        startActivity(new Intent(BindPhoneConfirmActivity.this, FourthActivity.class));
                        finish();
                    }
                } else {
                    startActivity(new Intent(BindPhoneConfirmActivity.this, ThirdActivity.class));
                    finish();
                }
            }

        }
    }

    public void failReasonMsg(String reason){
        if(msgDialog==null) {
            msgDialog = new AlertDialog.Builder(this, R.style.Dialog).create();
            msgDialog.show();
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_login_other_layout, null);
            msgDialog.getWindow().setContentView(view);
            Button button = (Button) view.findViewById(R.id.positiveButton);
            TextView msgTv = (TextView) view.findViewById(R.id.message);
            TextView titleTv = (TextView) view.findViewById(R.id.title);
            titleTv.setText("提示");
            msgTv.setText("" + reason);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    msgDialog.dismiss();
                    msgDialog=null;
                }
            });
        }
    }

    /**
     * 开始定时查询
     */
    private void beginTimer() {
        if (timeHandle == null) {
            smsCodeIsShowing=false;
            timeHandle = new Handler();
            //每五秒查询一次当前状态
            timeHandle.postDelayed(timer, time);
        }
    }

    /**
     * 结束定时查询
     */
    private void cancelTimer() {
        if (timeHandle != null) {
            timeHandle.removeCallbacks(timer);
            timeHandle = null;
        }
    }
}
